// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database(),
      _ = db.command,
      $ = _.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.action) {
    case 'consume_index': {
      return consume_index(event)
    }
    case 'consume_day': {
      return consume_day(event)
    }
    case 'consume_all': {
      return consume_all(event)
    }
    case 'consume_month': {
      return consume_month(event)
    }
    default: {
      return []
    }
  }
  
  // //aggregate 方法
  // const nowMonth = new Date().getMonth() + 1
  // const nowDay = new Date().getDate()
  // // 计算今日消费
  // db.collection('consume').aggregate()
  //   .project({
  //     month: $.month('$create_time'),
  //     day: $.dayOfMonth('$create_time'),
  //     money: '$money'
  //   })
  //   .match({ month: nowMonth, day: nowDay })
  //   .group({
  //     _id: null,
  //     today_consume: $.sum('$money')
  //   })
  //   .end()
  //   .then(res => {
  //     wx.hideLoading()
  //     if (!res.list[0]) return
  //     let today_consume = res.list[0].today_consume
  //     this.setData({
  //       today_consume: today_consume.toFixed(2)
  //     })
  //   }, err => {
  //     console.log(err)
  //     wx.hideLoading()
  //   })
}

// 主页面今日消费总额和本月消费总额
async function consume_index() {
  const OPENID = cloud.getWXContext().OPENID,
        nowMonth = new Date().getMonth() + 1,
        nowDay = new Date().getDate()
  let data = {
    today_consume: 0,
    month_consume: 0
  }
  await db.collection('consume').aggregate()
    .project({
      month: $.month('$create_time'),
      day: $.dayOfMonth('$create_time'),
      money: '$money',
      openid: '$_openid'
    })
    .match({ month: nowMonth, day: nowDay, openid: OPENID })
    .group({
      _id: null,
      today_consume: $.sum('$money')
    })
    .end().then(res => {
      let list = res.list[0] || { today_consume: 0 }
      data.today_consume = list.today_consume.toFixed(2)
    })
  await db.collection('consume').aggregate()
    .project({
      month: $.month('$create_time'),
      money: '$money',
      openid: '$_openid'
    })
    .match({ month: nowMonth, openid: OPENID })
    .group({
      _id: null,
      month_consume: $.sum('$money')
    })
    .end().then(res => {
      let list = res.list[0] || { month_consume: 0 }
      data.month_consume = list.month_consume.toFixed(2)
    })
  return data
}

// 今日消费列表
async function consume_day() {
  const OPENID = cloud.getWXContext().OPENID,
        nowMonth = new Date().getMonth() + 1,
        nowDay = new Date().getDate()
  let data = []
  await db.collection('consume').aggregate()
    .project({
      month: $.month('$create_time'),
      day: $.dayOfMonth('$create_time'),
      money: '$money',
      openid: '$_openid',
      className: '$className',
      content: '$content',
      time: $.dateToString({
        date: '$create_time',
        format: '%H:%M',
        timezone: 'Asia/Shanghai'
      })
    })
    .match({ month: nowMonth, day: nowDay, openid: OPENID })
    .end().then(res => {
      data = res.list
      data.map(item => {
        item.money = item.money.toFixed(2)
      })
    })
  return data
}

// 所有月份列表
async function consume_all() {
  const OPENID = cloud.getWXContext().OPENID,
        nowMonth = new Date().getMonth() + 1,
        nowDay = new Date().getDate()
  let data = []
  await db.collection('consume').aggregate()
    .match({ _openid: OPENID })
    .project({
      month: $.month('$create_time'),
      money: '$money',
      create_time: '$create_time',
      className: '$className',
      content: '$content',
      openid: '$_openid'
    })
    .bucket({
      groupBy: '$month',
      boundaries: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      default: 'other',
      output: {
        money: $.sum('$money')
      }
    })
    .sort({
      _id: -1
    })
    .end()
    .then(res => {
      data = res.list
      data.map(item => {
        if (item.money <= 100 && item.money >= 0) item.className = 'green-border'
        if (item.money <= 500 && item.money >= 101) item.className = 'yellow-border'
        if (item.money <= 1000 && item.money >= 501) item.className = 'orange-border'
        if (item.money <= 5000 && item.money >= 1001) item.className = 'orange-red-border'
        if (item.money > 5000) item.className = 'red-border'
        item.money = parseFloat(item.money).toFixed(2)
      })
    }, err => {
      console.log(err)
    })
  return data
}

// 月消费列表
async function consume_month(event) {
  const OPENID = cloud.getWXContext().OPENID,
        nowMonth = new Date().getMonth() + 1,
        nowDay = new Date().getDate()
  let m = parseFloat(event.month), 
      data = [],
      num = 20
  if (event.page) {
    num = (parseFloat(event.page) - 1) * 20
  }
  await db.collection('consume').aggregate()
    .project({
      month: $.month('$create_time'),
      money: '$money',
      create_time: '$create_time',
      time: $.dateToString({
        date: '$create_time',
        format: '%Y-%m-%d %H:%M',
        timezone: 'Asia/Shanghai'
      }),
      className: '$className',
      content: '$content',
      openid: '$_openid'
    })
    .match({ openid: OPENID, month: m })
    .sort({
      create_time: -1
    })
    .skip(num)
    .end()
    .then(res => {
      data = res.list
      data.map(item => {
        item.money = item.money.toFixed(2)
      })
    }, err => {
      console.log(err)
    })
  return data
}